<template>
  <div class="search-container">
    <form action="/" class="search">
      <!-- 事件监听 -->
      <van-search v-model="searchText" show-action placeholder="请输入搜索关键词" background="#3296fa" @search="onSearch"
        @cancel="$router.back()" @focus="isResultShow=false" />
    </form>
    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :q="searchText" />

    <!-- 搜索历史 -->
    <search-history v-else-if="!searchText" :searchHistory="searchHistoryList" @deleteId="deleteId"
      @searchHistory="onSearch" />

    <!-- 搜索联想建议 -->
    <search-suggestion @searchSuggest="onSearch" v-else :searchText="searchText" />
  </div>
</template>

<script>
import SearchHistory from './componets/search-history.vue'
import SearchResult from './componets/search-result.vue'
import SearchSuggestion from './componets/search-suggestion.vue'
// 导入本地存储
import { setItem, getItem } from '@/utils/storage.js'
// 定义本地存储常量
const SEARCHHISTORY = 'search_history'
export default {
  name: 'SearchPage',
  data () {
    return {
      searchText: '',
      // 控制搜索见过显示
      isResultShow: false,
      // 存历史记录数据
      searchHistoryList: [] || getItem(SEARCHHISTORY)
    }
  },
  methods: {
    // 删除单个
    deleteId (id) {
      this.searchHistoryList.splice(id, 1)
    },
    onSearch (val) {
      // console.log(e)
      // this.$toast(e)
      // 更新搜索内容
      this.searchText = val
      // 存储搜索历史数据  判断是否重复  最新记录放前面  set去重返回为set数组需要[...set]专为普通数组
      const index = this.searchHistoryList.findIndex(item => item === val)
      if (index !== -1) {
        this.searchHistoryList.splice(index, 1)
      }
      this.searchHistoryList.unshift(val)
      this.isResultShow = true
    },
    onCancel () {
      this.$toast('取消')
    }
  },
  computed: {},
  watch: {
    searchHistoryList (val) {
      // 此时的val 为最新的searchHistory数组
      setItem(SEARCHHISTORY, val)
    }
  },
  filters: {},
  components: { SearchHistory, SearchSuggestion, SearchResult },
  created () { },
  mounted () { }
}
</script>

<style lang='less' scoped>
.search-container {
  .search {
    padding-top: 106px;

    .van-search {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      z-index: 1;
    }

    .van-search__action {
      color: #fff;
    }
  }
}
</style>
